from django.contrib.admin import ModelAdmin as RawModelAdmin
from django.contrib import admin
import os
import uuid
from django.contrib.admin import site
from django.core.files.uploadedfile import InMemoryUploadedFile
from tuntun.settings import ALIYUN_OSS
from apps.system.models import SystemSetting as SS
import oss2
import time
from oss2.models import PutObjectResult
from oss2.http import Response
import json
import base64
from PIL import Image
from apps.storage.models import PublicFile


class ModelAdmin(RawModelAdmin):
    def save_to_tmp_file(self, in_memory_file: InMemoryUploadedFile):
        if in_memory_file:
            ext = in_memory_file.name.split('.')[-1]
            tmp_file = os.path.join('/tmp', uuid.uuid4().hex+'.'+ext)
            with open(tmp_file, 'wb+') as f:
                for chunk in in_memory_file.chunks():
                    f.write(chunk)
            return tmp_file
        else:
            return None

    def related_aliyun_oss_file(self, url):
        meta = {'mimeType': '*/*'}
        ext = url.split('.')[-1]
        key = '/'.join(url.split('//')[-1].split('/')[1:])
        if ext.lower() in ['png', 'jpeg', 'jpg', 'gif']:
            meta.update({
                'size': 0,
                'width': 0,
                'height': 0,
                'mimeType': 'image/%s' % ext,
            })
        public_file = PublicFile.objects.create(
            name=key, meta_data=meta, url=ALIYUN_OSS['oss_cdn_endpoint'] + '/' + key,
            mime_type=meta['mimeType'])
        return public_file.pk

    def put_file_to_aliyun_oss(self, in_memory_file):
        tmp_file = self.save_to_tmp_file(in_memory_file)
        if tmp_file is None:
            return None
        meta = {'mimeType': '*/*'}
        ext = tmp_file.split('.')[-1]
        if ext.lower() in ['png', 'jpeg', 'jpg', 'gif']:
            i = Image.open(tmp_file)
            meta.update({
                'size': in_memory_file.size,
                'width': i.size[0],
                'height': i.size[1],
                'mimeType': 'image/%s' % ext,
            })

        token = SS.get_aliyun_oss_sts_token()
        auth = oss2.StsAuth(token['access_key_id'], token['access_key_secret'], token['security_token'])
        bucket = oss2.Bucket(auth, ALIYUN_OSS['oss_endpoint_without_bucket'], ALIYUN_OSS['bucket'])
        key = "system/%s/%s.%s" % (time.strftime('%Y/%m%d/%H'), uuid.uuid4().hex, ext)
        meta['filename'] = key
        result = bucket.put_object_from_file(key, tmp_file)  # type: PutObjectResult
        if result.status != 200:
            raise Exception("上传文件错误")
        public_file = PublicFile.objects.create(name=key, meta_data=meta, url=ALIYUN_OSS['oss_endpoint']+'/'+key, mime_type=meta['mimeType'])
        return public_file.pk